package com.tuyan.aixiang.activity.config;

import android.Manifest;
import android.content.Intent;
import android.net.wifi.ScanResult;

import com.flyco.dialog.widget.NormalListDialog;
import com.jaychan.view.MultipleTextView;
import com.tuyan.aixiang.R;
import com.tuyan.aixiang.activity.add.AddDeviceActivity;
import com.tuyan.aixiang.common.BaseActivity;
import com.tuyan.aixiang.common.lang.ListHelper;
import com.tuyan.aixiang.common.lang.VoidFunction;
import com.tuyan.aixiang.model.YsDevice;
import com.tuyan.aixiang.util.Log;
import com.tuyan.aixiang.util.StringUtil;
import com.tuyan.aixiang.util.ToastUtil;
import com.tuyan.aixiang.util.WifiUtil;

import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.widget.AppCompatEditText;
import butterknife.BindView;
import butterknife.OnClick;
//import pub.devrel.easypermissions.AfterPermissionGranted;
//import pub.devrel.easypermissions.EasyPermissions;

public class WifiConfigActivity extends BaseActivity<WifiConfigPresenter> implements WifiConfig.View {

    private static final String TAG = "WifiConfigActivity";

    @BindView(R.id.mtv_title_hint)
    MultipleTextView mtvTitleHint;

    @BindView(R.id.mtv_device_ap_name)
    MultipleTextView mtvApName;

    @BindView(R.id.mtv_device_ap_pass)
    MultipleTextView mtvApPass;

    @BindView(R.id.et_wifi_name)
    AppCompatEditText etWifiName;

    @BindView(R.id.et_wifi_pass)
    AppCompatEditText etWifiPass;

    private YsDevice ysDevice;

    @Override
    public void bindView() {
        super.bindView();
        fitSystemWindow(R.color.colorPure);
        Intent intent = getIntent();
        ysDevice = (YsDevice) intent.getSerializableExtra("device");
        if (null == ysDevice) {
            ToastUtil.makeShort("设备信息错误");
            finish();
        }
        iPresenter.init(ysDevice);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_wifi_config;
    }

    @Override
    protected WifiConfigPresenter createPresenter() {
        return new WifiConfigPresenter();
    }

//    @AfterPermissionGranted(8847)
//    public void withFinePermission(VoidFunction func) {
//        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
//        if (EasyPermissions.hasPermissions(this, perms)) {
//            func.call();
//        } else {
//            EasyPermissions.requestPermissions(this, getString(R.string.request_fine), 8847, perms);
//        }
//    }

    @Override
    public void showDeviceInfo(YsDevice device) {

        setDeviceInfo(device);
//        switch (device.getModelType()) {
//            case DeviceModel.JY_BW01:
//                showGasDetectInfo(device);
//                break;
//            case DeviceModel.CS_T4_B:
//
//                break;
//            case DeviceModel.CS_C6HC_3B1WFR:
//
//                break;
//            case DeviceModel.CS_A2_32W:
//
//                break;
//            default:
//                break;
//        }
    }

    private void setDeviceInfo(YsDevice device) {
        mtvTitleHint.setContentText(device.getModelType());

        mtvApName.setContentText(device.getSsid());
        mtvApPass.setContentText(device.getPassword());
    }

    private void showGasDetectInfo(YsDevice device) {
        mtvTitleHint.setContentText(device.getDisplayName());

        mtvApName.setContentText(device.getSsid());
        mtvApPass.setContentText(device.getPassword());
    }

    @Override
    public void showWifiList() {
        withLocationPermission(() -> {
            List<ScanResult> results = WifiUtil.getInstance().getWifiList();
            ListHelper.forEach(results, r -> {
                Log.d(TAG, r.SSID);
            });
        });
    }

    @Override
    public void configSuccess() {
        runOnUiThread(() -> {
            hideLoading();
            ToastUtil.makeLong("请等待设备提示连接至WiFi后进行设备添加");
            Intent intent = new Intent(this, AddDeviceActivity.class);
            intent.putExtra("device", ysDevice);
            startActivity(intent);
            finish();
        });
    }

    @Override
    public void configFailed(int code) {
        hideLoading();
        runOnUiThread(() -> {

        switch (code) {
            case 15:
                // TODO: 2018/7/24 超时
                ToastUtil.makeShort("超时");
                hideLoading();

                break;
            case 1:
                // TODO: 2018/7/24 参数错误
                ToastUtil.makeShort("参数错误");
                hideLoading();

                break;
            case 2:
                // TODO: 2018/7/24 设备ap热点密码错误
                ToastUtil.makeShort("设备ap热点密码错误");
                hideLoading();

                break;
            case 3:
                // TODO: 2018/7/24  连接ap热点异常
                ToastUtil.makeShort("连接ap热点异常");
                hideLoading();

                break;
            case 4:
                // TODO: 2018/7/24 搜索WiFi热点错误
                ToastUtil.makeShort("搜索WiFi热点错误");
                hideLoading();

                break;
            default:
//                ToastUtil.makeShort("未知错误" + code);
                break;
        }
        });
    }
//                 更多错误码请见枚举类 EZConfigWifiErrorEnum 相关说明
//                EZConfigWifiErrorEnum

//    @OnClick(R.id.btn_search_device)
//    public void deviceSearch() {
//        iPresenter.deviceSearch();
//    }

    @OnClick(R.id.btn_device_connect)
    public void deviceConnect() {

        String ssid = getFormText(etWifiName);
        String pass = getFormText(etWifiPass);
        if(StringUtil.isBlank(ssid)) {
            ToastUtil.makeShort("请选择接入WiFi");
            return;
        }
        showLoading(true);
        iPresenter.deviceConnect(ssid, pass);
    }

    @OnClick(R.id.et_wifi_name)
    public void selectWifi() {
        List<ScanResult> wifis = WifiUtil.getInstance().getWifiList();
        if(wifis.size() == 0) {
            ToastUtil.makeLong("未获取到wifi列表,请打开定位服务和wifi开关后重试");
//            WifiUtil.getInstance().openSetting(this);
            return;
        }
        List<String> wifiNames = new ArrayList<>();
        if(null != wifis && wifis.size() > 0) {
            ListHelper.forEach(wifis, w -> {
                wifiNames.add(w.SSID);
            });
        }
        NormalListDialog wifiListDialog = new NormalListDialog(this, wifiNames.toArray(new String[wifiNames.size()]));
        wifiListDialog.isTitleShow(false)
                .itemTextColor(getResources().getColor(R.color.textDark))
                .layoutAnimation(null)
                .show();
        wifiListDialog.setOnOperItemClickL((parent, view, position, id) -> {
                String wifiName = wifiNames.get(position);
                etWifiName.setText(wifiName);
                wifiListDialog.hide();
        });
    }

    @OnClick(R.id.btn_switch_wifi)
    public void switchWifi() {
        WifiUtil.getInstance().openSetting(this);
    }

    @OnClick(R.id.btn_copy_pass)
    public void copyPass() {
        iPresenter.copyPass();
    }

    @OnClick(R.id.iv_back)
    public void onBack() {finish();}

}